"""
    视图模块
"""
import django_filters
from django.shortcuts import render
from django.views.decorators.cache import cache_page
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import mixins
from rest_framework.decorators import action

from rest_framework.filters import OrderingFilter
from rest_framework.generics import ListAPIView, RetrieveAPIView, DestroyAPIView
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet, GenericViewSet

from api import models, serializers

from api.models import College


class MyPagination(PageNumberPagination):
    """estates 的分页配置"""
    page_size = 5
    page_size_query_param = 'size'
    max_page_size = 50


@cache_page(timeout=60*60*24, cache='default')
def index(request):
    """主页"""
    return render(request, 'page.html')


class CollegeView(ListAPIView):
    """学院接口"""
    queryset = College.objects.all()
    serializer_class = serializers.CollegeSerializer
    pagination_class = MyPagination


class ClassViewSet(mixins.RetrieveModelMixin,
                   mixins.DestroyModelMixin,
                   mixins.ListModelMixin,
                   GenericViewSet):
    """班级接口"""
    queryset = models.class_m.objects.all()
    serializer_class = serializers.ClassSerializer

    @action(methods=('GET',), detail=True)
    def students(self, requset, pk):
        classm = self.get_object()
        queryset = models.Student.objects.filter(class_m=classm)
        return Response(serializers.StudentSimpleSerializer(queryset, many=True).data)


class StudentFilterSet(django_filters.FilterSet):
    """学生筛选器"""
    name = django_filters.CharFilter(lookup_expr='contains')
    addr = django_filters.CharFilter(lookup_expr='contains')
    class_m = django_filters.NumberFilter()

    class Meta:
        model = models.Student
        fields = ('name', 'addr', 'class_m',)


class StudentViewSet(mixins.DestroyModelMixin,
                     mixins.ListModelMixin,
                     GenericViewSet):
    """学生接口"""
    queryset = models.Student.objects.all()
    serializer_class = serializers.StudentSerializer
    pagination_class = MyPagination
    filter_backends = (DjangoFilterBackend, OrderingFilter)
    filter_class = StudentFilterSet
    ordering = ('id',)